package mobilesmil.activity;

import java.io.File;
import java.util.ArrayList;

import mobilesmil.activity.composer.ComposerActivity;
import mobilesmil.adapter.FileBrowserAdapter;
import mobilesmil.services.SmilMessages;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.NotificationManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
/**
 *This activity can be used to browse for specific file types on the root sd card.
 *These include the common types that are supported by Android.  There are several settings audio, video, image and text.
 *Default setting is for .smil files.    
 */
public class FileBrowserActivity extends ListActivity {
	
	private ArrayList<String> mSmilFiles = new ArrayList<String>();
	private String mPlayerTask;
	private String mPlayFile;
	private String mComposerTask;
	private String mEditFile;
	private String mFileNameKey;
	private String mFileNameValue;
	private boolean mReturnValue;
	
	private static final byte DIALOG_OPTION_PLAY_ID = 0;
	private static final byte DIALOG_OPTION_EDIT_ID = 1;
	private static final byte DIALOG_OPTION_SEND_ID = 2;
	private static final byte DIALOG_OPTION_CANCEL_ID = 3;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// look up the notification manager service
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // cancel the notification that we started in IncomingMessage
        nm.cancel(9);
		
        //this will allow for the background to show through when scrolling is happening
        this.getListView().setCacheColorHint(Color.TRANSPARENT);
        
        //get all of the extra keys and values that might be coming through in the message
		mPlayerTask = this.getString(R.string.playerTask);
		mPlayFile = this.getString(R.string.play);
		mComposerTask = this.getString(R.string.composerTask);
		mEditFile = this.getString(R.string.edit);
		mFileNameKey = this.getString(R.string.fileName);
		
		String fileType = "";
		
		fileType = getFileType(savedInstanceState);
		setReturnStatus(savedInstanceState);
		
		File sdcard = new File(Environment.getExternalStorageDirectory().toString());
		
		String[] allFiles = sdcard.list();
		
		//are there any files in the sd card root directory
		if(allFiles != null)
		{
			//filter them based upon file type
			for(int index = 0; index < allFiles.length; index++)
			{
				if(fileType.equalsIgnoreCase(this.getString(R.string.text)))
				{
					if(allFiles[index].endsWith(".txt") == true)
						mSmilFiles.add(allFiles[index]);
				}
				//mp3 m4a
				else if(fileType.equalsIgnoreCase(this.getString(R.string.audio)))
				{
					if((allFiles[index].endsWith(".mp3") == true) || (allFiles[index].endsWith(".m4a") == true))
						mSmilFiles.add(allFiles[index]);
				}
				//mp4 mpeg mpg 3gp
				else if(fileType.equalsIgnoreCase(this.getString(R.string.video)))
				{
					if((allFiles[index].endsWith(".mp4") == true) || 
							(allFiles[index].endsWith(".mpeg") == true) || 
							(allFiles[index].endsWith(".mpg") == true) ||
							(allFiles[index].endsWith(".3gp") == true))
						mSmilFiles.add(allFiles[index]);
				}
				//jpg gif bmp png
				else if(fileType.equalsIgnoreCase(this.getString(R.string.image)))
				{
					if((allFiles[index].endsWith(".gif") == true) ||
							(allFiles[index].endsWith(".bmp") == true) ||
							(allFiles[index].endsWith(".png") == true) ||
							(allFiles[index].endsWith(".jpg") == true))
						mSmilFiles.add(allFiles[index]);
				}
				else
				{
					if(allFiles[index].endsWith(this.getString(R.string.smil)) == true)
						mSmilFiles.add(allFiles[index]);
				}
				
				
			}
		}
		setContentView(R.layout.simple_list);
		FileBrowserAdapter adapter = new FileBrowserAdapter(this,android.R.layout.simple_list_item_1, mSmilFiles);
		setListAdapter(adapter);
		
		ListView messageView = getListView();
		
		messageView.setOnItemClickListener(new OnItemClickListener() {
		    public void onItemClick(AdapterView<?> parent, View view,
		            int position, long id) {
		    		mFileNameValue = ((TextView) view).getText().toString();
		    		
		    		//for use by another activity
			    	if(mReturnValue)
			    	{
			    		Intent file = new Intent();
			    		file.putExtra(mFileNameKey, mFileNameValue);
			    		setResult(RESULT_OK, file);
			    		finish();
			    	}
			    	//for use if opened by the home activity
			    	else
			    	{
			    		showDialog(DIALOG_OPTION_PLAY_ID);
			    	}
		        }
		      });
	}
	
	/**
	 * Takes a saved instance and extracts the fileType.
	 * If there is no saved instance it extracts the file type from the extras of the 
	 * @param savedInstanceState
	 * @return
	 */
	private String getFileType(Bundle savedInstanceState)
	{
		String intentString = "";
		
		if(savedInstanceState != null)
			intentString = savedInstanceState.getString("fileType");
		else
			intentString = null;

		if(intentString == null)
		{
			Bundle extras = getIntent().getExtras();
			if(extras != null)
			{
				if(getIntent().hasExtra("fileType"))
					intentString = extras.getString("fileType");
				else
					intentString = "";
			}
		}
		
		return intentString;
		
	}
	
	/**
	 * Decides whether or not this file browser was started to return a value or was started from the main activity
	 * @param savedInstanceState
	 */
	private void setReturnStatus(Bundle savedInstanceState)
	{
		String intentString = "";
		//is there a saved instance?
		if(savedInstanceState != null)
			//yes, get the intent string
			intentString = savedInstanceState.getString("managerTask");
		else
			//no then we need to check the intent
			intentString = null;

		//if there was a saved instance then we dont need to search for an intent
		if(intentString == null)
		{
			Bundle extras = getIntent().getExtras();
			if(extras != null)
			{
				if(getIntent().hasExtra("managerTask"))
					intentString = extras.getString("managerTask");
				else
					intentString = "";
			}
			else
				intentString = "";
		}
		
		//if this was called to browse then we need to return a file otherwise we dont return
		if(intentString.equalsIgnoreCase("browse"))
		{
			mReturnValue = true;
		}
		else
		{
			mReturnValue = false;
		}
	}


	@Override
	protected Dialog onCreateDialog(int id) 
	{
		Dialog dialog;
		final CharSequence[] items = {"Play", "Edit", "Send", "Cancel"};
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle("Task");
    	builder.setItems(items, new DialogInterface.OnClickListener() {
    	    public void onClick(DialogInterface dialog, int item) { 
    	        switch(item) 
    	        {
	    			case DIALOG_OPTION_PLAY_ID:
	    				markAsPlayed();
	    				playSmil();
	    				break;
	    			case DIALOG_OPTION_EDIT_ID:
	    				markAsPlayed();
	    				editSmil();
	    				break;
	    			case DIALOG_OPTION_SEND_ID:
	    				markAsPlayed();
	    				sendSmil();
	    				break;
	    			case DIALOG_OPTION_CANCEL_ID:
	    				break;
    	        }
    	    }});
    	
    	dialog = builder.create();
		return dialog;
	}
	
	/**
	 * This marks a message as played so it will not be bolded in the file browser
	 */
	private void markAsPlayed() {
		SmilMessages.setReceivedAndPlayed(this, mFileNameValue);
	}
	
	/**
	 * Launches PlayerActivity with an intent.
	 */
	private void playSmil()
	{
		Intent play = new Intent(getApplicationContext(), PlayerActivity.class);
		play.putExtra(mPlayerTask, mPlayFile);
		play.putExtra(mFileNameKey, mFileNameValue);
		
		startActivity(play);
		this.finish();
	}
	
	/**
	 * Launches composerActivity with an intent.
	 */
	private void editSmil()
	{
		Intent edit = new Intent(getApplicationContext(), ComposerActivity.class);
		edit.putExtra(mComposerTask, mEditFile);
		edit.putExtra(mFileNameKey, mFileNameValue);
		
		startActivity(edit);
		this.finish();
	}
	
	/**
	 * Launches SendActivity with an intent.
	 */
	private void sendSmil()
	{
		Intent send = new Intent(getApplicationContext(), SendActivity.class);
		send.putExtra(this.getString(R.string.sendTask), this.getString(R.string.send));
		send.putExtra(mFileNameKey, mFileNameValue);
		
		startActivity(send);
	}
	
	/**
	 * Will retrieve the next a smil file based upon the smilFile passed into the function.  It will return the next one if next is true and the previous if next is false
	 * @param next
	 * @param currentSmilFile
	 * @return
	 */
	public static String getFile(boolean next, String currentSmilFile)
	{
		File sdcard = new File(Environment.getExternalStorageDirectory().toString());
		String[] allFiles = sdcard.list();
		ArrayList<String> smilList = new ArrayList<String>();
		int indexOfReturnFile = -1;
		int numFiles = -1;
		
		
		if (allFiles != null)
		{
			
			for(int index = 0; index < allFiles.length; index++)
			{
				if (allFiles[index].endsWith(".smil"))
				{
					smilList.add(allFiles[index]);
					numFiles++;
				}
				
				if(allFiles[index].equalsIgnoreCase(currentSmilFile))
					indexOfReturnFile = numFiles;
			}
			
			if(numFiles != -1)
			{
				if(next)
				{
					indexOfReturnFile++;
					if(indexOfReturnFile == numFiles+1)
						indexOfReturnFile = 0;
				}
				else
				{
					indexOfReturnFile--;
					if(indexOfReturnFile == -1)
						indexOfReturnFile = numFiles;
				}
			}
		}
		
		if(indexOfReturnFile == -1)
			return null;
		else
			return smilList.get(indexOfReturnFile);
	}
}
